package CB_C19;

import javax.swing.JFileChooser.*;
import java.net.URL;
import javax.media.*;
import javax.media.protocol.*;
import java.io.*;
import javax.media.datasink.*;

/**Save Created on 10.11.2009. <br>
 * <br>
 * Our Class to Save the video, contains a processor<br>
 * @author Sebastian Czekierski, Stefan Blumberger
 */

public class Save implements ControllerListener,DataSinkListener
{
    /**DataSink to Render the media to destination*/
    DataSink sink;
    /**output*/
    DataSource output;
    /**Datasource input*/
    DataSource ds;
    /**Save Destination*/
    MediaLocator out;
    Format[] formats;
    /**Processor*/
    Processor proc;
    /**Save Path from FileChooser*/
    URL save_path;
    String type;
    Processor in;
    
        public Save(DataSource ds, URL save_path,Processor in)
        {
            this.ds = ds;
            this.save_path = save_path;
            this.in = in;
        }

        
        public void init() throws IOException, NoProcessorException, NoDataSourceException
        {

          
            
            out = new MediaLocator(save_path);
            proc = Manager.createProcessor(ds);
            proc.addControllerListener(this);
            proc.configure();
        }
    public String getType()
    {
        return "mov";
    }
    public synchronized void controllerUpdate(ControllerEvent event)
    {
        if(event instanceof ConfigureCompleteEvent)
        {
            type = com.sun.media.MimeManager.getMimeType("mov");
            type = ContentDescriptor.mimeTypeToPackageName(type);
            proc.setContentDescriptor(new FileTypeDescriptor(type));

            proc.realize();
        }
        if (event instanceof RealizeCompleteEvent)
         {
             output = proc.getDataOutput();
             if(output == null)
             {
                System.out.println("fail-null");
             }
             else
             {
                System.out.println("Saving....");
             }
             try
             {
                 sink = Manager.createDataSink(output, out);
             } catch (NoDataSinkException ex) {
                 ex.printStackTrace();
             }
            sink.addDataSinkListener(this);
            try {
                this.sink.open();
                this.sink.start();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            proc.start();
            in.start();
        }
         if(event instanceof EndOfMediaEvent)
         {
             System.out.println("done");
             proc.close();
         }
    }
        
    public void dataSinkUpdate(DataSinkEvent ev)
    {
        if(ev instanceof EndOfStreamEvent)
        {
            System.out.println("EndOfStreamEvent_sink");
            this.sink.close();
        }
        if(ev instanceof DataSinkErrorEvent)
        {
            System.out.println("DataSinkErrorEvent");
        }
     }
}
